
const http = require('http');
const https = require('https');

const express = require('express')
const app = express()
const port = 3000
const SQLHelper = require('./SQLHelper')
///雪花算法生成id
const snowflake = require('./snowflake')
var bodyParser = require('body-parser')

///解析body中间件
app.use(bodyParser.json({ limit: '100mb' }));

// let SQLHelper = require('./SQLHelper')
// SQLHelper('select count(*) from product').then(ret => {
//   console.log('I am mysql',ret);
// }) 



app.use(express.static('www'))

///token缓存
let tokens = {}



///登录拦截中间件
function loginRouter(req, res, next) {
  let token = req.headers.token
  if (token) {
    SQLHelper(`select * from session where id = ${token}`).then(ret => {
      if(ret.length){
        let session = ret[0]
        req.session = {
          userId:session.userId,
          userName:session.userName
        }
        next()
      }else{
        res.status(406).send({ errorMsg: '当前用户未登录' })
      }
    })
  } else {
    res.status(405).send({ errorMsg: '缺少token,请先进行登录' })
  }
}




///对小程序的所有接口进行拦截,排除用户登录，此时没有token，也没有用户信息
///除了登录的所有接口都需要登录验证拦截
app.use('/wx', loginRouter)


const formatTime = data => {
  const year = data.getFullYear()
  const month = data.getMonth() + 1
  const day = data.getDate()
  const hour = data.getHours()
  const minute = data.getMinutes()
  const second = data.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

///微信登陆
app.get('/wxlogin', (req, res, next) => {
  console.log(req)
  let code = req.query.code
  let appid = 'wx1f14e734d42b2c8c'
  let secret = '1b7ff819c6d614fe310e29adf955c7aa'
  https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
    ret.on('data', (ret) => {
      ret = JSON.parse(ret.toString())
      let openid = ret.openid
      if (!openid) {
        res.send({ errorMsg: ret.errMsg || '获取openid错误' })
      } else {///查询用户是否已经注册
        let queryMember = `select * from member where openId = '${openid}'`
        SQLHelper(queryMember).then(membersRet => {
          if (membersRet.length) {///用户已经存在
            ///挂载到req
            req.member = membersRet[0]
            next()
          } else {///用户不存在,使用openid注册用户
            SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
              ///注册成功返回新用户信息
              SQLHelper(queryMember).then(newMember => {
                ///挂载到req
                req.member = membersRet[0]
                next()
              })
            })
          }
        })
      }

    });

  }).on('error', (e) => {
    console.log(e)
    res.status(200).send({errorMsg: '获取openId错误'})
  });
}, (req, res) => {
  let member = req.member
  let token = snowflake()
  ///缓存到tokens到session表
  SQLHelper(`
  INSERT INTO session(id,userId,userName,inTime,platform)
  VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
  `).then(ret => {
    res.send({
      nickName: member.nickName,
      token,
      openId: member.openId,
      avatarUrl: member.avatarUrl,
      _id: member._id
    })
  })
})

///新增地址列表
///memberId 用户Id 必填
///receiver 收货人 必填
///phone 电话手机号 必填
///city 省市区 必填
///area 详情地址 非必填
app.post('/wx/address', (req, res) => {

  if (req.body.receiver && req.body.phone && req.body.city) {

    SQLHelper(`
       INSERT INTO address(memberId,receiver,phone,city,area,state)
       VALUES('${req.body.memberId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || 'null'}',1)
  `).then(ret => {
      res.send(ret)
    })

  } else {
    res.send({ errorMsg: '传入参数错误' })
  }

})

///修改用户信息
app.put('/wx/member', (req, res) => {
  ///
  let userInfo = req.body
  SQLHelper(`
  update member
  set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
  where _id = ${userInfo._id}
  `).then(ret => {
    console.log(ret)
    res.send({})
  })
})

///获取收货地址列表
///memberId  用户ID必填
app.get('/wx/address', (req, res) => {
  ///通过token获取session,获取用户信息
  // let session = tokens[req.headers.token]
  // let memberId = session._id
  if (req.session.userId) {
    SQLHelper(`
    select * from address where state = 1 and memberId = ${req.session.userId}
  `).then(ret => {
      res.send(ret)
    })
  } else {
    res.send({ errorMsg: '请传入memberId' })
  }
})


///新增收货地址
///memberId  用户ID必填
///receiver  用户收货人必填
///phone  用户手机号必填
///city  用户省市区必填
///area  用户详细地址非必填
app.put('/wx/address', (req, res) => {
  if (req.body.addressId) {
    ///需要修改的项
    let updateKey = ['receiver', 'phone', 'city', 'area']
    let updateValues = []
    for (let i = 0; i < updateKey.length; i++) {
      let key = updateKey[i], value = req.body[key]
      if (value) updateValues.push(`${key}='${value}'`)///判断哪些需要修改
    }
    // if(req.body.receiver){
    //   updateValues.push(`receiver=${req.body.receiver}`)
    // }
    SQLHelper(`UPDATE address set ${updateValues.join(',')} WHERE _id = ${req.body.addressId}`).then(ret => {
      res.send(ret)
    })
  } else {
    res.send({ errorMsg: '传入参数错误' })
  }
})

///删除地址:逻辑删除
///addressId  主码_id必填
app.delete('/wx/address', (req, res) => {
  let addressId = req.body.addressId
  if (addressId) {
    SQLHelper(`
    UPDATE address
    set state = 0
    WHERE _id = ${addressId}
  `).then(ret => {
      res.send(ret)
    })
  } else {
    res.send({ errorMsg: '请传入参数错误' })
  }
})

///获取收货详情
///address  地址_id必填
app.get('/wx/address/detail', (req, res) => {
  if (req.query.addressId) {
    SQLHelper(`
    select * from address where _id = ${req.query.addressId}
  `).then(ret => {
      res.send(ret.length ? ret[0] : { errorMsg: '未获取地址详情' })
    })
  } else {
    res.send({ errorMsg: '请传入addressId' })
  }
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

